package com.xg.frame.shiro;

import com.xg.frame.constant.SysConstant;
import com.xg.sys.entity.SysUser;
import com.xg.sys.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * shiro验证
 * @author dehuisun
 *
 */
@Component
public class MyRealm extends AuthorizingRealm{

	@Autowired
	private SysUserService sysUserService;

    @Autowired
    private RedisTemplate redisTemplate;

	/**
     * 必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo();
    }

    /**
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();

        if (token == null) {
            throw new AuthenticationException("token为空!");
        }
        // 校验token有效性
        SysUser user = this.checkToken(token);

        return new SimpleAuthenticationInfo(user, token, getName());
    }

    /**
     * 校验token的有效性
     */
    public SysUser checkToken(String token) throws AuthenticationException {
        // 解密获得username，用于和数据库进行对比
        String userId = JwtUtil.getUserId(token);
        if (userId == null) {
            throw new AuthenticationException("token非法");
        }

        SysUser user= sysUserService.getById(userId);
        if (user == null) {
            throw new AuthenticationException("用户不存在!");
        }
        // 判断用户状态
        if (SysConstant.STATUS_N.equals(user.getStatus())) {
            throw new AuthenticationException("账号已被锁定,请联系管理员!");
        }
        // 校验token是否超时失效 & 或者账号密码是否错误
        if (!jwtTokenRefresh(token, String.valueOf(user.getId()))) {
            throw new AuthenticationException("Token失效，请重新登录!");
        }

        return user;
    }

    /**
     * 刷新token
     */
    public boolean jwtTokenRefresh(String token, String userId) {
        String cacheToken = (String)redisTemplate.opsForValue().get(SysConstant.CATCHE_TOKEN + token);
        if (StringUtils.isNotEmpty(cacheToken)) {
            // 校验token有效性
            if (!JwtUtil.verify(cacheToken)) {
                String newToken = JwtUtil.sign(userId);
                // 设置超时时间
                redisTemplate.opsForValue().set(SysConstant.CATCHE_TOKEN + token,newToken, JwtUtil.expire * 2, TimeUnit.SECONDS);
            }
            return true;
        }
        return false;
    }



}
